package com.huzz.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huzz.entity.SysUser;
import com.huzz.mapper.SysUserMapper;
import com.huzz.model.SysUserCreateModel;
import com.huzz.model.SysUserQueryModel;
import com.huzz.model.SysUserUpdateModel;
import com.huzz.service.ISysUserService;
import com.huzz.util.entityutil.FieldUtil;
import com.huzz.util.entityutil.ModelUtil;
import com.huzz.vo.SysUserVO;
import com.huzz.util.body.DataBox;
import com.huzz.util.body.ResultCode;
import com.huzz.util.encryption.RSAUtils;
import com.huzz.util.exception.BizException;
import com.huzz.util.pinyin4j.Pinyin4jUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 系统用户-业务实现层
 *
 * @author 童年的纸飞机
 * @since 2023-06-06 20:05
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {


    @Value("${encryption.rsa.publicKey}")
    private String publicKey;

    /**
     * 系统用户Mapper
     */
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 根据进行ID查询SysUser
     *
     * @param id
     * @return
     */
    @Override
    public SysUserVO getSysUserById(Integer id) {
        SysUser sysUser = sysUserMapper.selectById(id);
        sysUser.setPassword("");
        return ModelUtil.transToSimilarEntity(sysUser, SysUserVO.class);
    }

    /**
     * 新增SysUser
     *
     * @param model
     * @return
     */
    @Override
    @Transactional
    public boolean createSysUser(SysUserCreateModel model) {
        String defaultPassword = Pinyin4jUtil.getPinYinHeadChar(model.getNickname().substring(0, 3)) + "0000";

        SysUser sysUser = ModelUtil.transToSimilarEntity(model, SysUser.class);
        FieldUtil.setCreatedAndUpdateField(sysUser);
        sysUser.setPassword(RSAUtils.encryption(defaultPassword, publicKey));
        sysUser.setDeleted(0);

        return sysUserMapper.insert(sysUser) > 0;
    }

    /**
     * 更新SysUser
     *
     * @param model
     * @return
     */
    @Override
    @Transactional
    public boolean updateSysUser(SysUserUpdateModel model) {
        if (sysUserMapper.selectById(model.getId()) == null) {
            throw new BizException(ResultCode.COMMON_FAIL.getCode(), "更新对象不存在");
        }

        SysUser sysUser = (SysUser) ModelUtil.transToSimilarEntity(model, SysUser.class);
        FieldUtil.setUpdateField(sysUser);

        return sysUserMapper.updateById(sysUser) > 0;
    }

    /**
     * 根据ID进行删除SysUser
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public boolean deleteSysUserById(Integer id) {
        if (sysUserMapper.selectById(id) == null) {
            throw new BizException(ResultCode.COMMON_FAIL.getCode(), "删除对象不存在");
        }

        return sysUserMapper.deleteById(id) > 0;
    }

    /**
     * 分页查询SysUser列表
     *
     * @param pageNum
     * @param pageSize
     * @param model
     * @return
     */
    @Override
    public IPage<SysUserVO> selectSysUserPage(Integer pageNum, Integer pageSize, SysUserQueryModel model) {
        QueryWrapper<SysUser> wrapper = getQueryWrapper(model);

        return sysUserMapper.selectSysUserVOList(new Page<>(pageNum, pageSize), wrapper);
    }

    /**
     * 查询SysUser列表
     *
     * @param model
     * @return
     */
    @Override
    public List<SysUser> selectSysUserList(SysUserQueryModel model) {
        QueryWrapper<SysUser> wrapper = getQueryWrapper(model);

        return sysUserMapper.selectList(wrapper);
    }

    /**
     * 导出SysUser列表
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @Override
    public void exportSysUserExcel(HttpServletRequest request, HttpServletResponse response, SysUserQueryModel model) {
        QueryWrapper<SysUser> wrapper = getQueryWrapper(model);

        List<SysUserVO> data = sysUserMapper.selectSysUserVOList(wrapper);

        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("系统用户列表", "SysUserVO"), SysUserVO.class, data);
        String fileName = String.format("系统用户_%d.xls", System.currentTimeMillis());
        response.setHeader("Content-Disposition", "attachment;Filename=" + fileName);
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        try {
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 批量编辑SysUser
     *
     * @param modelList
     * @return
     */
    @Override
    public DataBox<String> updateSysUserByList(List<SysUserUpdateModel> modelList) {
        List<SysUser> sysUserList = ModelUtil.transToSimilarList(modelList, SysUser.class);
        int i = 0;
        for (SysUser sysUser : sysUserList) {
            FieldUtil.setUpdateField(sysUser);
            i += sysUserMapper.updateById(sysUser);
        }

        return i > 0 ?
                DataBox.succeedBuilder("共" + i + "条记录更新成功, " + (sysUserList.size() - i) + "条记录更新失败") : DataBox.failedBuilder("更新失败");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Override
    public DataBox<String> deleteSysUserByIds(List<Integer> ids) {
        int i = sysUserMapper.deleteBatchIds(ids);
        return i > 0 ?
                DataBox.succeedBuilder("共" + i + "条记录被删除, " + (ids.size() - i) + "条记录删除失败") : DataBox.failedBuilder("删除失败");
    }

    /**
     * 查询条件
     *
     * @param model
     * @return
     */
    private QueryWrapper<SysUser> getQueryWrapper(SysUserQueryModel model) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();

        if (model.getDepartmentIds() != null && model.getDepartmentIds().length > 0) {
            wrapper.lambda().in(SysUser::getDepartmentId, model.getDepartmentIds());
        }

        // 根据 ids 进行查询
        if (model.getIds() != null && model.getIds().length > 0) {
            wrapper.lambda().in(SysUser::getId, model.getIds());
        }
        // 根据 注册时间区间 进行查询
        if (model.getTimeInterval() != null && model.getTimeInterval().length == 2) {
            wrapper.lambda().between(SysUser::getCreatedTime, model.getTimeInterval()[0], model.getTimeInterval()[1]);
        }
        // 根据 用户名 进行查询
        if (!StringUtils.isEmpty(model.getUsername())) {
            wrapper.lambda().like(SysUser::getUsername, model.getUsername());
        }
        // 根据 性别(男:1,女0) 进行查询
        if (null != model.getSex()) {
            wrapper.lambda().eq(SysUser::getSex, model.getSex());
        }
        // 根据 电话 进行查询
        if (!StringUtils.isEmpty(model.getPhone())) {
            wrapper.lambda().eq(SysUser::getPhone, model.getPhone());
        }
        // 根据 邮箱 进行查询
        if (!StringUtils.isEmpty(model.getEmail())) {
            wrapper.lambda().eq(SysUser::getEmail, model.getEmail());
        }
        // 根据 昵称 进行查询
        if (!StringUtils.isEmpty(model.getNickname())) {
            wrapper.lambda().like(SysUser::getNickname, model.getNickname());
        }
        // 查询 未删除 的记录
        wrapper.lambda().eq(SysUser::getDeleted, 0);
        // 根据 更新时间 进行降序
        wrapper.lambda().orderByDesc(SysUser::getUpdateTime);

        return wrapper;
    }

}